package com.yi.wood.web.ctrl;

import com.yi.wood.base.Result;
import com.yi.wood.base.ResultCodeEnum;
import com.yi.wood.entity.Goods;
import com.yi.wood.service.exception.BusinessException;
import com.yi.wood.web.ctrl.dto.GoodsDto;
import com.yi.wood.web.ctrl.dto.GoodsParam;
import com.yi.wood.web.service.GoodsProService;
import com.yi.wood.web.util.WoodBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Objects;

/**
 * Created by moyi on 2019/1/30 14:12
 *
 * @author moyi
 */
@Validated
@RestController
@RequestMapping(value = "/api/goods")
public class GoodsCtrl extends BaseCtrl {

    @Resource
    private GoodsProService goodsProService;

    /**
     * 查询商品列表
     * @param type 类型
     * @param name 商品名
     * @param goodsNo 商品编码
     * @param pageNum 分页参数
     * @param pageSize 分页参数
     * @return 分页商品列表
     */
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    public Object list(@RequestParam(defaultValue = "1") @Max(10) @Min(0) Integer type,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String goodsNo,
                       @RequestParam(defaultValue = "1") @Min(0) Integer pageNum,
                       @RequestParam(defaultValue = "10") @Min(1) @Max(50) Integer pageSize){
        Page<GoodsDto> page = goodsProService.pageGoodsList(name, goodsNo, pageNum, pageSize);
        return success(page);
    }

    /**
     * 添加商品
     * @param param 商品信息
     * @return 商品信息
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object addGoods(@RequestBody @Valid GoodsParam param){
        Goods goods = new Goods();
        BeanUtils.copyProperties(param, goods);
        goods = goodsProService.addData(goods);
        return success(goods);
    }

    /**
     * 更新商品
     * @param param 商品信息
     * @return 商品信息
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object updateGoods(@RequestBody GoodsParam param){
        Goods goods = goodsProService.queryById(param.getId());
        if (Objects.isNull(goods)){
            throw new BusinessException(new Result(ResultCodeEnum.NOT_FOUND, null));
        }
        BeanUtils.copyProperties(param, goods, WoodBeanUtils.getNullPropertyNames(param));

        goods = goodsProService.updateData(goods);
        return success(goods);
    }
}
